

import java.util.StringTokenizer;

public class Test {
	static final String NBSP = "&nbsp;";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String str = "three   spaces";
		String str2= "three &nbsp;&nbsp;space - Supplier 1";
		System.out.println(formatSpaces(str));
		System.out.println(formatSpaces(str2));
	}

	private static String formatSpaces(String str) {
		if (str == null) {
			return "";
		}

		final String SPACE = "\040";
		StringTokenizer tokenizer = new StringTokenizer(str, SPACE, true);
		StringBuilder sb = new StringBuilder(1024);

		boolean leadingSpace = true;
		boolean previousTokenIsASpace = false;

		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();

			if (token.equals(SPACE)) {
				if (leadingSpace || previousTokenIsASpace) {
					// This is a leading space or an adjacent space.
					sb.append(NBSP);
					continue;
				} else {
					// This is not a leading space or an adjacent space yet.
					sb.append(SPACE);
					previousTokenIsASpace = true;
					continue;
				}
			} else {
				// This is not a space. Append it, and set flags to false.
				sb.append(token);
				leadingSpace = false;
				previousTokenIsASpace = false;
				continue;
			}
		}

		String out = sb.toString();
		return out;
	}

}
